<!-- 后结算模块-财务管理-销售管理-开票推送oms -->
<template>
  <div class="invoice-list-box">
    <el-container class="partDetails is-vertical">
      <el-header
        height="auto"
        class="no-padding">
        <record-info
          class="common-ui"
          :record-form="recordFormDetail"
          :record-data="headerInfo" />
      </el-header>
      <SearchForm
        class="common-ui"
        label-width="120px"
        :data="invoiceSearchData"
        :compact-data="invoiceSearchData.slice(0,2)"
        show-collapse
        @searchForm="searchForm"
        @resetForm="resetForm"
        :submit-loading='submitLoading'
      />
      <el-row class="common-ui">
        <el-col
          class="product-info-left"
          :span="12">
          <p>销售产品总数：<span>{{ headerInfo.prodTotalCount }}</span></p>
          <p>品种数：<span>{{ headerInfo.prodVarietyCount }}</span></p>
          <p>金额合计（元）：<span style="color:red;">{{ headerInfo.orderTotalAmount | getFormatterPrice }}</span></p>
        </el-col>
        <el-col
          class="product-info-right"
          :span="12">
          <p v-show="notGouke">选中产品总数：<span>{{ cacheProData.prodTotalCount }}</span></p>
          <p v-show="notGouke">选中品种数：<span>{{ cacheProData.prodVarietyCount }}</span></p>
          <p v-show="notGouke">选中金额合计（元）：<span style="color:red;">{{ cacheProData.cacheAmountTotal | getFormatterPrice }}</span></p>
          <div class="product-btns">
            <el-button
              v-if="isGouke"
              size="mini"
              type="primary"
              class="batch-btn"
              @click="batchAddInvoice"
            >批量关联</el-button>
            <el-button
              v-if="notGouke"
              size="mini"
              type="primary"
              class="batch-btn"
              @click="toPushInvoice"
            >上传发票</el-button>
          </div>
        </el-col>
      </el-row>
      <el-editable
        ref="multipleTable"
        class="hospital-edit-box"
        :data="list"
        height="400"
        v-loading="submitLoading"
        :columns="activeTableColumns"
        @select-all="changeSelectAll"
        @select="changeSelect"
      >
        <!-- 发票详情 -->
        <template
          slot="default-mplatInvoiceStatus"
          slot-scope="scope">
          <el-button
            v-if="scope.row.mplatInvoiceStatus === 1"
            @click="toLookDetails(scope.row)"
            type="text">查看详情</el-button>
          <span
            v-if="scope.row.mplatInvoiceStatus === 2"
            style="color:red;">发票作废</span>
          <span
            v-if="scope.row.mplatInvoiceStatus === 3"
            style="color:red;">查无此票</span>
          <span v-if="scope.row.mplatInvoiceStatus === 4">查验中</span>
          <span v-if="!scope.row.mplatInvoiceStatus">待上传</span>
        </template>
        <!-- 发票影像 -->
        <template
          slot="default-invoiceUrl"
          slot-scope="scope">
          <div style="display:flex; justify-content: center;">
            <el-image
              v-if="scope.row.invoiceUrl"
              @click="toLookDetails(scope.row)"
              style="width: 23px; height: 16.6px;"
              :src="imageicon"
            />
          </div>
        </template>
        <template
          slot="default-pssRegistNo"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.pssRegistNo||!scope.row.pssRegistId"
            v-html="regisNoButton(scope.row, ['pssRegistNo', 'pssRegistId'])"
            @click="showPdfRegistion(scope.row.pssRegistId)"
            type="text"
          />
        </template>
        <template
          slot="default-hosRegistNo"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.hosRegistNo||!scope.row.hosRegistId"
            v-html="regisNoButton(scope.row, ['hosRegistNo', 'hosRegistId'])"
            @click="showPdfRegistion(scope.row.hosRegistId)"
            type="text"
          />
        </template>
        <template
          slot="default-busiType"
          slot-scope="scope">
          <el-select
            v-model="scope.row.busiType"
            clearable
            @change="changeBusiType($event, scope.row)"
            placeholder="请选择">
            <el-option
              v-for="item in scope.row.busiOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </template>
        <template
          slot="default-orderType"
          slot-scope="scope">
          <el-select
            v-model="scope.row.orderType"
            clearable
            placeholder="请选择">
            <el-option
              v-for="item in scope.row.orderOptions"
              :key="item.value"
              :title="item.label"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <pagination
        ref="page"
        :request-func="getList"
        @returnData="getTableData"
      />
      <el-dialog
        :title="dialogTitle"
        :visible.sync="batchDialogVisible"
        width="50%"
        @close="handleClose">
        <el-form
          ref="batchInvoiceForm"
          :model="batchInvoiceForm"
          :rules="batchInvoiceRules"
          label-width="100px">
          <el-form-item
            :label="'业务模式'"
            prop="busiType">
            <el-select
              v-model="batchInvoiceForm.busiType"
              clearable
              @change="changeBusiType"
              placeholder="请选择">
              <el-option
                v-for="item in OMS_BUSITYPE_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="'订单类型'"
            prop="orderType">
            <el-select
              v-model="batchInvoiceForm.orderType"
              clearable
              placeholder="请选择">
              <el-option
                v-for="item in orderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer">
          <el-button @click="handleClose">
            <i class="el-icon-circle-close"/>
            取 消</el-button>
          <el-button
            type="primary"
            @click="toBacthSetType(batchInvoiceForm)">
            <i class="el-icon-circle-check"/>
            确 定</el-button>
        </span>
      </el-dialog>
      <invoice-details
        :display-or-not="displayOrNotDetails"
        :invoice-url="activeInvoiceUrl"
        :invoice-no="activeInvoiceNo"
        @cancelDialog="cancelDialog" />
    </el-container>
  </div>
</template>

<script>
import {
  invoicePushColomns,
  invoiceFinanceColomns,
  recordFormDetail,
  statusArr,
  invoiceSearchData,
  OMS_BUSITYPE_OPTIONS
  // ORDER_TYPE_OPTIONS
} from './const'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import Pagination from '@components/custom-pagination'
import { attrItemList } from '@const/orderCenterApi'
import {
  distributorInvoiceById,
  distributorInvoiceItemById,
  yySettleInvoiceOrderHasInvoiceOrderItemInfo,
  distributorInvoicePushOMS,
  cacheInvoiceOrderItemInfo, // 缓存操作接口
  settleGetAmountofCache, // （后结算）配送商-获取缓存金额数据
  distributorInvoiceCheckInvoiceStatus, // （后结算）配送商-完成
  distributorInvoiceItemUpdate
} from '@const/beforeSettleApi'
import ElEditable from '@components/el-editable'
import invoiceDetails from '@/moduleComponents/beforeSettle/invoiceDetails/index.vue'
import SearchForm from '@components/businesscomponents/search'
import { cloneDeep, isObject, hasIn } from 'lodash'
import { getFormatterPrice } from '@const/filter'
import { getCertificate } from '@const/productCenterApiV2'
import { regisNoButton, showPdfRegistion } from '@const/agencySaas'
// 明细详情地址
const detailRequestData = {
  GOUKE: distributorInvoiceItemById,
  UNGOUKE: yySettleInvoiceOrderHasInvoiceOrderItemInfo
}
const PAGE_TYPE = 'finance'
export default {
  components: { ElEditable, Pagination, RecordInfo, SearchForm, invoiceDetails },
  data () {
    return {
      imageicon: require('@assets/icon/beforeSettle/imageicon.png'),
      // 订单id/状态
      selectStatus: true,
      id: this.$route.query.id,
      orderStatus: Number(this.$route.query.orderStatus), // （1-待开票；2-已推送；3-已开票；4-验票完成；5-已撤销）
      goukePushBtns: [
        { type: 'primary', val: '暂存', handle: this.toStory },
        { type: 'primary', val: '推送T平台', handle: this.pushOMS }
      ],
      notGoukeBtns: [
        { type: 'primary', val: '完成', handle: this.toFinish }
      ],
      // 订单基础信息
      headerInfo: {}, // 基础数据
      cacheProData: {},
      recordFormDetail, // 基础数据表头
      // 表格相关数据
      batchInvoiceForm: {
        busiType: null,
        orderType: null
      },
      batchInvoiceRules: {
        busiType: [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        orderType: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      },
      selectList: [],
      batchDialogVisible: false,
      invoiceSearchData, // 详情分页-查询表头
      submitLoading: false, // 详情分页-loading
      list: [], // 详情分页-数据
      searchData: {}, // 详情分页-查询数据
      OMS_BUSITYPE_OPTIONS, // 详情分页-业务模式
      orderOptions: [], // 详情分页-订单类型
      dialogTitle: '',
      // 查看发票详情
      displayOrNotDetails: false,
      activeInvoiceUrl: '',
      activeInvoiceNo: ''
    }
  },
  computed: {
    // 非国科系公司，上传发票；国科系公司，有推送按钮；订单中的产品全部成功关联发票后，订单开票状态改为已开票，否则就是待开票
    // sourceType :订单来源  （1:非国科系公司
    type () {
      return this.$route.query.type
    },
    isGouke () {
      return [1].includes(this.orderStatus) && this.type === 'GOUKE'
    },
    notGouke () {
      return [1].includes(this.orderStatus) && this.type === 'UNGOUKE'
    },
    activeBtns () {
      return this.isGouke ? this.goukePushBtns : this.notGouke ? this.notGoukeBtns : []
    },
    activeTableColumns () {
      return this.isGouke ? invoicePushColomns : this.notGouke ? invoiceFinanceColomns : []
    }
  },
  mounted () {
    this.getBaseList(this.globalBtns)
  },
  filters: {
    getFormatterPrice
  },
  methods: {
    regisNoButton,
    showPdfRegistion,
    // 禁用所有右上按钮
    disabledAllbtn (arr = this.activeBtns) {
      let disArr = cloneDeep(arr)
      disArr.forEach(i => { i.disabled = true })
      this.globalBtns(disArr)
    },
    globalBtns (arr = this.activeBtns) {
      const btn = {
        type: 'btn',
        arr: cloneDeep(arr)
      }
      this.$store.commit('changeLayoutHandle', btn)
    },
    // 过滤模式-是否存在
    isHasType (val) {
      return val.busiType && val.orderType
    },
    getTypeList ({ itemDetailId, busiType, orderType }) {
      return {
        itemDetailId: itemDetailId,
        omsBusModel: busiType,
        omsOrderType: orderType
      }
    },
    // 暂存
    async toStory (list = this.list) {
      const body = list.map(this.getTypeList)
      if (!body.length) {
        this.$message.warning('请选择模式')
        return
      }
      const data = await this.$axios.$post(distributorInvoiceItemUpdate, body)
      if (data.code === '0') {
        this.$message.success('操作成功')
        this.$refs.page.Refresh()
      }
    },
    // 业务模式和订单类型联动
    changeBusiType (val, obj) {
      const orderOptions = val ? this.OMS_BUSITYPE_OPTIONS.find(item => Object.is(item.value, val)).children
        : []
      if (obj) {
        Object.assign(obj, { orderOptions, orderType: null })
        return
      }
      this.orderOptions = orderOptions
      this.batchInvoiceForm.orderType = null
    },
    // 选择订单项
    toBacthSetType (form) {
      this.$refs.batchInvoiceForm.validate(valid => {
        if (valid) {
          if (['GOUKE'].includes(this.type)) {
            const orderOptions = this.orderOptions
            this.selectList.forEach(item => {
              Object.assign(item, form, { orderOptions })
            })
            // this.toStory(this.selectList) 不请求
            this.batchDialogVisible = false
            this.batchInvoiceForm = {
              busiType: null,
              orderType: null
            }
          }
          if (['UNGOUKE'].includes(this.type)) {
            this.toPushInvoicePage()
          }
        }
      })
    },
    // 推送OMS
    async pushOMS (list = this.list) {
      this.goukePushBtns[1] = { type: 'primary', val: '推送T平台', disabled: true, handle: this.pushOMS }
      this.globalBtns()
      const busTypeForms = list.filter(this.isHasType).map(this.getTypeList)
      if (busTypeForms.length < this.list.length) {
        this.$message.warning('请选择模式')
        return
      }
      const body = {
        invoiceId: this.id,
        busTypeForms
      }
      const data = await this.$axios.$post(distributorInvoicePushOMS, body)
      if (data.code === '0') {
        this.$message.success('操作成功')
        this.$router.go(-1)
      }
      if (data.code || data.code === '0') {
        this.goukePushBtns[1] = { type: 'primary', val: '推送T平台', disabled: true, handle: this.pushOMS }
        this.globalBtns()
      }
    },
    // 搜索功能-点击查询
    searchForm (condition) {
      this.searchData = condition
      this.$refs.page.Refresh()
    },
    // 点击重置
    resetForm (condition) {
      this.searchData = condition
      this.$refs.page.Refresh()
    },
    // 基础信息
    async getBaseList () {
      const funcList = [...arguments]
      const body = {
        invoiceId: this.id
      }
      const data = await this.$axios.$post(distributorInvoiceById, body)
      const baseInfo = hasIn(data, 'payload') ? data.payload : {}
      Object.keys(baseInfo).forEach(key => {
        if (key === 'orderStatus') {
          // this.orderStatus = baseInfo[key]
          baseInfo[key] = statusArr[baseInfo[key]]
        }
        if (key === 'sourceType') {
          this.sourceType = baseInfo[key]
          baseInfo[key] = statusArr[baseInfo[key]]
        }
        this.$set(this.headerInfo, key, baseInfo[key] || '--')
      })
      funcList.forEach(item => {
        item && item()
      })
    },
    // 列表请求方法
    async getTableData (data) {
      if (['GOUKE'].includes(this.type)) {
        this.list = data
        // 处理联动select选择
        data.forEach(item => {
          const arr = this.OMS_BUSITYPE_OPTIONS.find(i => Object.is(i.value, item.busiType))
          const orderOptions = arr ? arr.children : []
          this.$set(item, 'orderOptions', orderOptions)
          this.$set(item, 'busiOptions', cloneDeep(OMS_BUSITYPE_OPTIONS))
        })
        this.submitLoading = false
      }
      if (['UNGOUKE'].includes(this.type)) {
        this.getSettleGetAmountofCache()
        this.list = data
        const cacheDeliverList = await this.getCacheDeliverList(3)// 获取缓存数据
        await this.$nextTick()
        let cacheList = cacheDeliverList.payload.orderItemId
        this.selectStatus = true
        this.list.forEach(item => {
          if (cacheList.includes(item.orderItemId)) {
            this.$refs.multipleTable.$refs.table.toggleRowSelection(item)
          }
        })
        this.selectStatus = false
        this.submitLoading = false
      }
    },
    // 列表请求方法/接口两个(国科系公司/非国科系公司)
    getList () {
      this.tableLoading = true
      // 地址选择
      const requestUrl = detailRequestData[this.type]
      const body = {
        orderId: this.id,
        ...this.searchData,
        ...this.$refs.page.page
      }
      return this.$axios.$post(requestUrl, body)
    },
    // 批量添加发票号
    batchAddInvoice () {
      if (!this.selectList.length) {
        this.dialogTitle = '批量关联'
        this.$message.warning('至少选择一项')
      } else {
        this.batchDialogVisible = true
      }
    },
    handleClose () {
      this.batchDialogVisible = false
      this.batchInvoiceForm = {
        busiType: null,
        orderType: null
      }
    },

    // 非国科系--订单完成
    async toFinish (list = this.list) {
      const responseData = await this.$axios.$post(distributorInvoiceCheckInvoiceStatus, {
        orderId: this.id
      })
      responseData.code === '0' && this.$router.go(-1)
    },
    // 查看发票详情
    toLookDetails (val) {
      this.activeInvoiceUrl = val.invoiceUrl
      this.activeInvoiceNo = val.invoiceNo
      this.displayOrNotDetails = true
    },
    cancelDialog () {
      this.activeInvoiceUrl = ''
      this.activeInvoiceNo = ''
      this.displayOrNotDetails = false
      this.$refs.page.Refresh()
    },
    // 去上传票
    toPushInvoicePage () {
      this.$router.push({
        path: '/common/uploadInvoice',
        query: {
          id: this.id,
          type: PAGE_TYPE,
          ...this.batchInvoiceForm
        }
      })
    },
    // 批量添加发票号
    async toPushInvoice () {
      const cacheDeliverList = await this.getCacheDeliverList(3)// 获取缓存数据
      if (cacheDeliverList.payload.orderItemId.length > 0) {
        this.dialogTitle = '请选择订单业务类型'
        this.batchDialogVisible = true
      }
      if (!cacheDeliverList.payload.orderItemId.length) {
        this.$confirm('此操作将对订单全部产品关联发票，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const data = await this.getCacheDeliverList(2)
            this.batchDialogVisible = true
          })
          .catch(() => {})
      }
    },
    // 详情-发货详情
    getCacheDeliverList (orderItemIdStatus, orderItemId = []) {
      const url = cacheInvoiceOrderItemInfo
      const data = {
        orderItemId,
        orderId: this.id, // 订单id
        orderItemIdStatus, // 订单明细状态0:删除缓存   ;1:存进缓存   2:用户全选  3：根据主键查询
        type: PAGE_TYPE
      }
      return this.$axios.$post(url, data)
    },
    // 获取缓存数据合计
    getSettleGetAmountofCache () {
      const url = settleGetAmountofCache
      const data = {
        orderId: this.id, // 订单id
        type: PAGE_TYPE
      }
      this.$axios.$post(url, data).then(res => {
        if (res.code === '0') {
          const cacheProData = hasIn(res, 'payload') ? res.payload : {}
          this.cacheProData = cacheProData
        }
      })
        .catch(err => {
          console.log(err)
        })
    },
    // 开票-单选走暂存
    async changeSelect (selection, row) {
      if (this.notGouke && !this.selectStatus) {
        let status = selection.includes(row) ? 1 : 0
        let orderItemId = [row.orderItemId]
        // 操作缓存getCacheDeliverList  获取缓存合计getSettleGetAmountofCache
        const data = await this.getCacheDeliverList(status, orderItemId)
        this.getSettleGetAmountofCache()
      }
      // 响应的勾选数据
      if (this.isGouke) {
        this.selectList = selection
      }
    },
    // 开票-全选走暂存
    async changeSelectAll (selection) {
      if (this.notGouke && !this.selectStatus) {
        let ids = this.list.map(item => item.orderItemId)
        const data = await this.getCacheDeliverList(selection.length ? 1 : 0, ids)
        this.getSettleGetAmountofCache()
      }
      // 响应的勾选数据
      if (this.isGouke) {
        this.selectList = selection
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import '../m-front-common/pc/assets/var.less';
.invoice-list-box {
  background: @bgColor;
  height: 100%;
  .no-padding.el-header {
    padding: 0;
  }
  .common-ui {
    padding: 8px 0;
    min-height: 42px;
    background: #fff;
    margin-bottom: 16px;
  }
  .partDetails {
    height: 100%;
    .batch-btn.el-button span {
      color: white;
      margin-right: 0;
      font-size: 14px;
    }
    .batch-btn.el-button {
      position: absolute;
      right: 0;
    }
    .product-info-left {
      padding: 0 0 0 8px;
      display: flex;
      p {
        margin-right: 20px;
        span {
          color: blue;
        }
      }
    }
    .product-info-right {
      display: flex;
      justify-content: flex-end;
      p {
        margin-right: 20px;
        span {
          color: blue;
        }
      }
    }
    .product-btns {
      min-width: 120px;
    }
  }
}
</style>
